export function getElementProps<T extends keyof HTMLElement>(
  selector: string,
  props: T[]
): MyRecord<T, string> {
  const ele = document.querySelector(selector) as HTMLElement;
  return props.reduce((acc, prop) => {
    return {
      ...acc,
      [prop]: ele[prop],
    };
  }, {} as MyRecord<T, string>);
}

export function extractTextFromHtml(htmlString: string): string {
  const div = document.createElement("div");
  div.innerHTML = htmlString.trim();
  const text = div.textContent || div.innerText;
  return text;
}

export function getElementBottomCenterAxis(selector: string) {
  const ele = document.getElementById(selector);
  if (ele) {
    // 获取元素的边界矩形（包括边框、滚动条、边距等）
    const rect = ele.getBoundingClientRect();

    const DEFAULT_Y_OFFSET = 20;

    // 获取页面的滚动位置
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;

    // 计算元素中间底部的X和Y坐标
    const middleBottomX = rect.left + rect.width / 2;

    // 但上面的middleBottomY计算有误，因为bottom已经是元素底部到视口的距离，所以应该是：
    const middleBottomY =
      rect.top + rect.height / 2 + scrollTop + DEFAULT_Y_OFFSET;

    // 输出坐标
    return {
      x: middleBottomX,
      y: middleBottomY,
    };
  }
}

export const getEditorDom = (function () {
  const ROOT_ID = "edit_container";
  let editorDom: HTMLElement | null = null;
  return function () {
    return editorDom || (editorDom = document.getElementById(ROOT_ID));
  };
})();

export function getWordCountFromHtml(htmlString: string) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(htmlString, "text/html");
  const BLOCK_TAG = [
    "BR",
    "P",
    "H1",
    "H2",
    "H3",
    "H4",
    "H5",
    "H6",
    "UL",
    "OL",
    "LI",
  ];

  let text = "";

  function traverse(node: HTMLElement | Node) {
    if (node.nodeType === Node.TEXT_NODE) {
      // 更准确地处理中文字符
      const words = node
        .textContent!.split(/([\u4e00-\u9fff])/g)
        .filter((word) => word.length > 0);
      text += words.join(" ");
    } else if (BLOCK_TAG.includes((node as HTMLElement).tagName)) {
      text += "\n";
    } else {
      for (let child of node.childNodes) {
        traverse(child);
      }
    }
  }

  traverse(doc.body);

  // 替换连续的多个换行符为一个
  text = text.replace(/\n+/g, "\n");

  // 替换标点符号为占位符 $ , 不匹配中文
  text = text.replace(/[^\w\s^(\u4e00-\u9fff)]/g, " $");

  return text.split(/\s+/g).filter((word) => word.length > 0).length;
}

export function getLastDeepestNode(node: Node) {
  let childNodes = node?.childNodes;
  let lastNode = childNodes[childNodes?.length - 1];
  if (lastNode && lastNode.childNodes.length > 0) {
    return getLastDeepestNode(lastNode);
  } else {
    return lastNode;
  }
}

export function setHTMLElementStyle(
  target: HTMLElement,
  styles: MyPartial<MyRecord<keyof CSSStyleDeclaration, string>>
) {
  for (const key in styles) {
    target.style[key] = styles[key] || "";
  }
}
